package com.taxi.gateway.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author: Ruomeng
 * @Date: 2024/3/24
 * @Description : 断言工厂 自定义路由
 * 使用例子: 上线了v1 v2 v3 3个版本服务，
 * 想要用户只能访问version1版本服务，version2 version3版本不可访问 可以使用断言 自定义路由版本
 * @Version: 1.0
 */
@Component
public class MyVersionRoutePredicateFactory extends AbstractRoutePredicateFactory<MyVersionRoutePredicateFactory.MyConfig> {

    public MyVersionRoutePredicateFactory() {
        super(MyConfig.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(new String[]{"version"});
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyConfig config) {

        return (ServerWebExchange serverWebExchange) -> {
            String version = serverWebExchange.getRequest().getQueryParams().getFirst("version");
            System.out.println("version:" + version);
            if (version != null && version.equals(config.getVersion())) {
                return true;
            } else {
                return false;
            }
        };
    }

    public static class MyConfig {
        private String version;

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }
    }
}
